package com.softWang.job.util;

import com.softWang.common.utils.ExceptionUtil;
import com.softWang.common.utils.SpringUtils;
import com.softWang.common.utils.StringUtil;
import com.softWang.job.constants.ScheduleConstants;
import com.softWang.job.mapper.JobLogMapper;
import com.softWang.job.mapper.JobManageMapper;
import com.softWang.job.po.JobLog;
import com.softWang.job.po.JobManage;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 抽象quartz调用
 *
 * @author ruoyi
 */
public abstract class AbstractQuartzJob implements Job
{
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException
    {
        JobManage sysJob = new JobManage();
        BeanUtils.copyProperties(context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES), sysJob);
        try
        {
            before(context, sysJob);
            if (sysJob != null)
            {
                doExecute(context, sysJob);
            }
            after(context, sysJob, null);
        }
        catch (Exception e)
        {
            log.error("任务执行异常  - ：", e);
            after(context, sysJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     */
    protected void before(JobExecutionContext context, JobManage sysJob)
    {
        threadLocal.set(new Date());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     */
    protected void after(JobExecutionContext context, JobManage sysJob, Exception e)
    {
        Date startTime = threadLocal.get();
        threadLocal.remove();

        final JobLog sysJobLog = new JobLog();
        sysJobLog.setJobName(sysJob.getJobName());
        sysJobLog.setJobGroup(sysJob.getJobGroup());
        sysJobLog.setJobClassName(sysJob.getJobClassName());
        sysJobLog.setParameter(sysJob.getParameter());
        sysJobLog.setSysJobOnce(sysJob.getSysJobOnce());
        sysJobLog.setCreateTime(LocalDateTime.now());
        sysJobLog.setJobId(sysJob.getJobId());
        long runMs = new Date().getTime() - startTime.getTime();
        long duration = (long) runMs/1000;
        sysJobLog.setDuration(duration);
        if (e != null)
        {
            sysJobLog.setStatus("1");
            String errorMsg = StringUtil.substring(ExceptionUtil.getExceptionMessage(e),0,2000);
            sysJobLog.setExceptionInfo(errorMsg);
        }
        else
        {
            sysJobLog.setStatus("0");
        }

        //一次性任务，更改任务表状态为已结束
        if(sysJob.getSysJobOnce().equals("1")){
            sysJob.setStatus("1");
            sysJob.setFinish("1");
            SpringUtils.getBean(JobManageMapper.class).updateById(sysJob);
        }

        // 写入数据库当中
        SpringUtils.getBean(JobLogMapper.class).insert(sysJobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, JobManage sysJob) throws Exception;
}
